
import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import {
  Settings,
  Plus,
  Edit,
  Trash2,
  Search,
  Loader
} from "lucide-react";
import { InvokeLLM } from "@/api/integrations";

// 新增：中国省份及其下属地市数据结构
const CHINA_REGIONS = {
  "北京市": ["全市"],
  "天津市": ["全市"],
  "上海市": ["全市"],
  "重庆市": ["全市"],
  "河北省": ["全省", "石家庄市", "唐山市", "秦皇岛市", "邯郸市", "邢台市", "保定市", "张家口市", "承德市", "沧州市", "廊坊市", "衡水市"],
  "山西省": ["全省", "太原市", "大同市", "阳泉市", "长治市", "晋城市", "朔州市", "晋中市", "运城市", "忻州市", "临汾市", "吕梁市"],
  "辽宁省": ["全省", "沈阳市", "大连市", "鞍山市", "抚顺市", "本溪市", "丹东市", "锦州市", "营口市", "阜新市", "辽阳市", "盘锦市", "铁岭市", "朝阳市", "葫芦岛市"],
  "吉林省": ["全省", "长春市", "吉林市", "四平市", "辽源市", "通化市", "白山市", "松原市", "白城市", "延边朝鲜族自治州"],
  "黑龙江省": ["全省", "哈尔滨市", "齐齐哈尔市", "鸡西市", "鹤岗市", "双鸭山市", "大庆市", "伊春市", "佳木斯市", "七台河市", "牡丹江市", "黑河市", "绥化市"],
  "江苏省": ["全省", "南京市", "无锡市", "徐州市", "常州市", "苏州市", "南通市", "连云港市", "淮安市", "盐城市", "扬州市", "镇江市", "泰州市", "宿迁市"],
  "浙江省": ["全省", "杭州市", "宁波市", "温州市", "嘉兴市", "湖州市", "绍兴市", "金华市", "衢州市", "舟山市", "台州市", "丽水市"],
  "安徽省": ["全省", "合肥市", "芜湖市", "蚌埠市", "淮南市", "马鞍山市", "淮北市", "铜陵市", "安庆市", "黄山市", "滁州市", "阜阳市", "宿州市", "六安市", "亳州市", "池州市", "宣城市"],
  "福建省": ["全省", "福州市", "厦门市", "莆田市", "三明市", "泉州市", "漳州市", "南平市", "龙岩市", "宁德市"],
  "江西省": ["全省", "南昌市", "景德镇市", "萍乡市", "九江市", "新余市", "鹰潭市", "赣州市", "吉安市", "宜春市", "抚州市", "上饶市"],
  "山东省": ["全省", "济南市", "青岛市", "淄博市", "枣庄市", "东营市", "烟台市", "潍坊市", "济宁市", "泰安市", "威海市", "日照市", "临沂市", "德州市", "聊城市", "滨州市", "菏泽市"],
  "河南省": ["全省", "郑州市", "开封市", "洛阳市", "平顶山市", "安阳市", "鹤壁市", "新乡市", "焦作市", "濮阳市", "许昌市", "漯河市", "三门峡市", "南阳市", "商丘市", "信阳市", "周口市", "驻马店市"],
  "湖北省": ["全省", "武汉市", "黄石市", "十堰市", "宜昌市", "襄阳市", "鄂州市", "荆门市", "孝感市", "荆州市", "黄冈市", "咸宁市", "随州市", "恩施土家族苗族自治州"],
  "湖南省": ["全省", "长沙市", "株洲市", "湘潭市", "衡阳市", "邵阳市", "岳阳市", "常德市", "张家界市", "益阳市", "郴州市", "永州市", "怀化市", "娄底市", "湘西土家族苗族自治州"],
  "广东省": ["全省", "广州市", "深圳市", "珠海市", "汕头市", "佛山市", "韶关市", "湛江市", "肇庆市", "江门市", "茂名市", "惠州市", "梅州市", "汕尾市", "河源市", "阳江市", "清远市", "东莞市", "中山市", "潮州市", "揭阳市", "云浮市"],
  "广西壮族自治区": ["全区", "南宁市", "柳州市", "桂林市", "梧州市", "北海市", "防城港市", "钦州市", "贵港市", "玉林市", "百色市", "贺州市", "河池市", "来宾市", "崇左市"],
  "海南省": ["全省", "海口市", "三亚市", "三沙市", "儋州市"],
  "四川省": ["全省", "成都市", "自贡市", "攀枝花市", "泸州市", "德阳市", "绵阳市", "广元市", "遂宁市", "内江市", "乐山市", "南充市", "眉山市", "宜宾市", "广安市", "达州市", "雅安市", "巴中市", "资阳市", "阿坝藏族羌族自治州", "甘孜藏族自治州", "凉山彝族自治州"],
  "贵州省": ["全省", "贵阳市", "六盘水市", "遵义市", "安顺市", "毕节市", "铜仁市", "黔西南布依族苗族自治州", "黔东南苗族侗族自治州", "黔南布依族苗族自治州"],
  "云南省": ["全省", "昆明市", "曲靖市", "玉溪市", "保山市", "昭通市", "丽江市", "普洱市", "临沧市", "楚雄彝族自治州", "红河哈尼族彝族自治州", "文山壮族苗族自治州", "西双版纳傣族自治州", "大理白族自治州", "德宏傣族景颇族自治州", "怒江傈僳族自治州", "迪庆藏族自治州"],
  "西藏自治区": ["全区", "拉萨市", "日喀则市", "昌都市", "林芝市", "山南市", "那曲市", "阿里地区"],
  "陕西省": ["全省", "西安市", "铜川市", "宝鸡市", "咸阳市", "渭南市", "延安市", "汉中市", "榆林市", "安康市", "商洛市"],
  "甘肃省": ["全省", "兰州市", "嘉峪关市", "金昌市", "白银市", "天水市", "武威市", "张掖市", "平凉市", "酒泉市", "庆阳市", "定西市", "陇南市", "临夏回族自治州", "甘南藏族自治州"],
  "青海省": ["全省", "西宁市", "海东市", "海北藏族自治州", "黄南藏族自治州", "海南藏族自治州", "果洛藏族自治州", "玉树藏族自治州", "海西蒙古族藏族自治州"],
  "宁夏回族自治区": ["全区", "银川市", "石嘴山市", "吴忠市", "固原市", "中卫市"],
  "新疆维吾尔自治区": ["全区", "乌鲁木齐市", "克拉玛依市", "吐鲁番市", "哈密市", "昌吉回族自治州", "博尔塔拉蒙古自治州", "巴音郭楞蒙古自治州", "阿克苏地区", "克孜勒苏柯尔克孜自治州", "喀什地区", "和田地区", "伊犁哈萨克自治州", "塔城地区", "阿勒泰地区"],
  "内蒙古自治区": ["全区", "呼和浩特市", "包头市", "乌海市", "赤峰市", "通辽市", "鄂尔多斯市", "呼伦贝尔市", "巴彦淖尔市", "乌兰察布市", "兴安盟", "锡林郭勒盟", "阿拉善盟"],
  "台湾省": ["全省"],
  "香港特别行政区": ["全区"],
  "澳门特别行政区": ["全区"]
};

const SYSTEM_SETTING_TEMPLATES = [
  {
    key: "cache_ttl",
    name: "缓存过期时间",
    description: "系统缓存数据的存活时间（秒）",
    value: 3600,
    type: "number",
    is_system_required: false
  },
  {
    key: "max_file_size",
    name: "最大文件上传大小",
    description: "允许上传的最大文件大小（MB）",
    value: 50,
    type: "number",
    is_system_required: false
  },
  {
    key: "default_language",
    name: "默认语言",
    description: "系统默认界面语言",
    value: "zh-CN",
    type: "string",
    is_system_required: false
  },
  {
    key: "enable_debug",
    name: "调试模式",
    description: "是否启用调试模式",
    value: false,
    type: "boolean",
    is_system_required: false
  },
  {
    key: "backup_retention_days",
    name: "备份保留天数",
    description: "系统备份文件保留的天数",
    value: 30,
    type: "number",
    is_system_required: false
  },
  {
    key: "map_cache_region",
    name: "地图缓存区域",
    description: "选择要缓存的地理区域（系统必需配置）",
    value: {
      name: "大理市",
      bounds: {
        north: 26.7,
        south: 24.8,
        west: 99.7,
        east: 101.1
      },
      center: [25.6916, 100.2417]
    },
    type: "json",
    is_system_required: true
  }
];

const SYSTEM_REQUIRED_configKeyS = [
  'map_cache_region',
];

const isSystemRequired = (configKey) => {
  return SYSTEM_REQUIRED_configKeyS.some(requiredKey =>
    configKey.includes(requiredKey)
  );
};

export default function SystemSettingsManager({ configs, onSave, onDelete, isLoading }) {
  const [showForm, setShowForm] = useState(false);
  const [editingConfig, setEditingConfig] = useState(null);
  const [formData, setFormData] = useState({
    configKey: "",
    settingName: "",
    setting_value: "",
    value_type: "string",
    description: "",
    is_active: true
  });
  // New state variables
  const [selectedProvince, setSelectedProvince] = useState("");
  const [selectedCity, setSelectedCity] = useState(""); // 新增城市选择状态
  const [isQueryingCoords, setIsQueryingCoords] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    let processedValue = formData.setting_value;

    switch (formData.value_type) {
      case 'number':
        processedValue = parseFloat(formData.setting_value);
        if (isNaN(processedValue)) {
          alert('请输入有效的数字');
          return;
        }
        break;
      case 'boolean':
        processedValue = formData.setting_value === 'true' || formData.setting_value === true;
        break;
      case 'json':
        try {
          processedValue = JSON.parse(formData.setting_value);

          // 对地图配置进行特殊验证
          if (formData.configKey.includes('map_cache_region')) {
            if (!processedValue.name || !processedValue.bounds || !processedValue.center) {
              alert('地图配置必须包含 name、bounds 和 center 字段');
              return;
            }

            if (!Array.isArray(processedValue.center) || processedValue.center.length !== 2) {
              alert('center 字段必须是包含两个数字的数组');
              return;
            }

            const { bounds } = processedValue;
            if (!bounds || typeof bounds.north === 'undefined' || typeof bounds.south === 'undefined' || typeof bounds.west === 'undefined' || typeof bounds.east === 'undefined') {
              alert('bounds 字段必须包含 north、south、west、east 四个数值');
              return;
            }
            
            // 关键修复：将表单中修改的名称同步到JSON对象内部
            processedValue.name = formData.settingName;
          }
        } catch (e) {
          alert('JSON格式错误，请检查语法: ' + e.message);
          return;
        }
        break;
      default:
        processedValue = formData.setting_value;
    }

    // 修复：确保地图配置数据结构正确
    const configData = {
      configKey: formData.configKey,
      config_type: "system_setting",
      config_value: formData.configKey.includes('map_cache_region') ?
        processedValue : // 地图配置直接存储JSON数据
        {
          name: formData.settingName,
          value: processedValue,
          type: formData.value_type,
          is_system_required: isSystemRequired(formData.configKey)
        },
      description: formData.description,
      is_active: formData.is_active
    };

    console.log('准备保存的配置数据:', JSON.stringify(configData, null, 2));

    try {
      await onSave(configData, editingConfig ? editingConfig.id : null);
      handleCancel();
    } catch (error) {
      console.error('保存配置失败:', error);
      alert('保存配置失败: ' + error.message);
    }
  };

  const handleEdit = (config) => {
    setEditingConfig(config);
    let settingValue;
    let valueType;
    let settingName;

    // Handle map_cache_region specifically for editing
    if (config.configKey.includes('map_cache_region')) {
        settingValue = JSON.stringify(config.config_value, null, 2);
        // 修复：确保从JSON内部获取名称
        settingName = config.config_value.name || config.configKey; 
        valueType = 'json';
    } else {
        settingValue = config.config_value.value !== undefined ?
            (typeof config.config_value.value === 'object' ?
                JSON.stringify(config.config_value.value, null, 2) :
                config.config_value.value.toString()) : "";
        settingName = config.config_value.name || config.configKey;
        valueType = config.config_value.type || "string";
    }

    setFormData({
      configKey: config.configKey,
      settingName: settingName,
      setting_value: settingValue,
      value_type: valueType,
      description: config.description || "",
      is_active: config.is_active !== undefined ? config.is_active : true
    });
    setShowForm(true);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingConfig(null);
    setFormData({
      configKey: "",
      settingName: "",
      setting_value: "",
      value_type: "string",
      description: "",
      is_active: true
    });
    setSelectedProvince(""); // Reset selected province on cancel
    setSelectedCity(""); // Reset selected city on cancel
  };

  const handleSafeDelete = (config) => {
    const isRequired = isSystemRequired(config.configKey);
    if (isRequired) {
      alert('此配置项为系统必需配置，无法删除。如需修改请使用编辑功能。');
      return;
    }

    if (window.confirm('确定要删除此配置项吗？删除后无法恢复。')) {
      onDelete(config.id);
    }
  };

  const handleUseTemplate = (template) => {
    const timestamp = Date.now();
    let templateValue = template.value;

    setFormData({
      configKey: `setting_${template.key}_${timestamp}`,
      settingName: template.name,
      setting_value: template.type === 'json' ? JSON.stringify(templateValue, null, 2) : templateValue.toString(),
      value_type: template.type,
      description: template.description,
      is_active: true
    });
    setSelectedProvince(""); // Clear selections when using a template
    setSelectedCity("");
  };

  // 修改：查询地理坐标的函数，支持省市两级
  const handleQueryCoordinates = async () => {
    if (!selectedProvince) {
      alert("请先选择一个省份。");
      return;
    }
    
    const queryLocation = selectedCity && selectedCity !== "全省" && selectedCity !== "全市" && selectedCity !== "全区" 
      ? selectedProvince + selectedCity // Combine province and city for better LLM context
      : selectedProvince;
    
    setIsQueryingCoords(true);
    try {
      // **修复：优化AI指令，明确要求坐标顺序**
      const prompt = `查询中国'${queryLocation}'的地理边界经纬度范围（bounds）和中心点经纬度（center），并以JSON格式返回。确保JSON对象包含'name', 'bounds', 和 'center'三个键。其中bounds应包含north, south, west, east四个浮点数值。center应为一个包含两个浮点数的数组，格式为 [latitude, longitude] (纬度在前，经度在后)。`;
      const jsonSchema = {
        type: "object",
        properties: {
          name: { type: "string", description: "省份或城市名称" },
          bounds: {
            type: "object",
            properties: {
              north: { type: "number" },
              south: { type: "number" },
              west: { type: "number" },
              east: { type: "number" }
            },
            required: ["north", "south", "west", "east"]
          },
          center: {
            type: "array",
            items: { type: "number" },
            description: "中心点坐标，格式为 [latitude, longitude]"
          }
        },
        required: ["name", "bounds", "center"]
      };

      const response = await InvokeLLM({
        prompt: prompt,
        addContextFromInternet: true,
        responseJsonSchema: jsonSchema
      });

      if (response && response.bounds && response.center) {
        setFormData(prev => ({
          ...prev,
          setting_value: JSON.stringify(response, null, 2),
          // 当查询坐标时，设置名称应该与查询的地区一致
          settingName: response.name || queryLocation // Use name from response if available, otherwise queryLocation
        }));
      } else {
        throw new Error("AI未能返回有效的坐标数据结构。");
      }
    } catch (error) {
      console.error("查询坐标失败:", error);
      alert(`查询坐标失败: ${error.message}`);
    } finally {
      setIsQueryingCoords(false);
    }
  };

  const renderValueInput = () => {
    // 关键修改：为地图缓存区域提供特殊UI
    if (formData.configKey.includes('map_cache_region')) {
      const availableCities = selectedProvince ? CHINA_REGIONS[selectedProvince] || [] : [];
      
      return (
        <div className="space-y-4 p-4 border rounded-lg bg-gray-50">
          <p className="text-sm text-gray-600">请选择省份和具体地区，系统将自动获取其地理坐标范围。</p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
            <Select onValueChange={(value) => { setSelectedProvince(value); setSelectedCity(""); }} value={selectedProvince}>
              <SelectTrigger>
                <SelectValue placeholder="请选择省份..." />
              </SelectTrigger>
              <SelectContent>
                {Object.keys(CHINA_REGIONS).map(province => (
                  <SelectItem key={province} value={province}>{province}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            
            <Select onValueChange={setSelectedCity} value={selectedCity} disabled={!selectedProvince || availableCities.length === 0}>
              <SelectTrigger>
                <SelectValue placeholder={selectedProvince ? "请选择地区..." : "先选择省份"} />
              </SelectTrigger>
              <SelectContent>
                {availableCities.map(city => (
                  <SelectItem key={city} value={city}>{city}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <Button 
            type="button" 
            onClick={handleQueryCoordinates} 
            disabled={isQueryingCoords || !selectedProvince}
            className="w-full"
          >
            {isQueryingCoords ? (
              <Loader className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Search className="w-4 h-4 mr-2" />
            )}
            查询坐标
          </Button>
          
          <div>
            <Label>生成的坐标数据 (自动生成)</Label>
            <Textarea
              value={formData.setting_value}
              readOnly
              rows={8}
              className="font-mono text-sm bg-white"
              placeholder="选择省份和地区，然后点击“查询坐标”..."
            />
          </div>
        </div>
      );
    }

    switch (formData.value_type) {
      case 'boolean':
        return (
          <div className="flex items-center space-x-2">
            <Switch
              checked={formData.setting_value === 'true' || formData.setting_value === true}
              onCheckedChange={(checked) => setFormData({...formData, setting_value: checked.toString()})}
            />
            <Label>{formData.setting_value === 'true' || formData.setting_value === true ? '启用' : '禁用'}</Label>
          </div>
        );
      case 'json':
        return (
          <Textarea
            value={formData.setting_value}
            onChange={(e) => setFormData({...formData, setting_value: e.target.value})}
            placeholder='{"key": "value"}'
            rows={6}
            className="font-mono text-sm"
            required
          />
        );
      case 'number':
        return (
          <Input
            type="number"
            value={formData.setting_value}
            onChange={(e) => setFormData({...formData, setting_value: e.target.value})}
            placeholder="请输入数值"
            required
          />
        );
      default:
        return (
          <Input
            value={formData.setting_value}
            onChange={(e) => setFormData({...formData, setting_value: e.target.value})}
            placeholder="请输入设置值"
            required
          />
        );
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h3 className="text-xl font-semibold">系统设置</h3>
        <Button
          onClick={() => setShowForm(true)}
          className="bg-green-600 hover:bg-green-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加系统设置
        </Button>
      </div>

      {showForm && (
        <Card className="shadow-lg border-0">
          <CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50 border-b">
            <CardTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5 text-green-600" />
              {editingConfig ? '编辑系统设置' : '添加系统设置'}
              {editingConfig && isSystemRequired(editingConfig.configKey) && (
                <Badge className="bg-blue-100 text-blue-700">
                  系统必需配置
                </Badge>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            {!editingConfig && (
              <div className="mb-6">
                <Label className="text-sm font-medium text-gray-700 mb-3 block">
                  选择预设模板（可选）
                </Label>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {SYSTEM_SETTING_TEMPLATES.map((template, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      onClick={() => handleUseTemplate(template)}
                      className="justify-start h-auto p-3 text-left"
                    >
                      <div>
                        <div className="font-medium">{template.name}</div>
                        <div className="text-xs text-gray-500 mt-1">
                          {template.description}
                        </div>
                      </div>
                    </Button>
                  ))}
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="configKey">配置键名 *</Label>
                  <Input
                    id="configKey"
                    value={formData.configKey}
                    onChange={(e) => setFormData({...formData, configKey: e.target.value})}
                    placeholder="例如: setting_cache_ttl"
                    required
                    disabled={editingConfig && isSystemRequired(editingConfig.configKey)}
                    className={editingConfig && isSystemRequired(editingConfig.configKey) ? "bg-gray-100" : ""}
                  />
                  {editingConfig && isSystemRequired(editingConfig.configKey) && (
                    <p className="text-xs text-blue-600 mt-1">系统必需配置的键名不可修改</p>
                  )}
                </div>
                <div>
                  <Label htmlFor="settingName">设置名称 *</Label>
                  <Input
                    id="settingName"
                    value={formData.settingName}
                    onChange={(e) => setFormData({...formData, settingName: e.target.value})}
                    placeholder="例如: 缓存过期时间"
                    required
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="value_type">值类型 *</Label>
                <Select
                  value={formData.value_type}
                  onValueChange={(value) => setFormData({...formData, value_type: value})}
                  disabled={formData.configKey.includes('map_cache_region')} // Disable type change for map config
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="string">字符串</SelectItem>
                    <SelectItem value="number">数字</SelectItem>
                    <SelectItem value="boolean">布尔值</SelectItem>
                    <SelectItem value="json">JSON对象</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="setting_value">设置值 *</Label>
                {renderValueInput()}
              </div>

              <div>
                <Label htmlFor="description">描述</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({...formData, description: e.target.value})}
                  placeholder="设置描述..."
                  rows={3}
                />
              </div>

              <div className="flex items-center space-x-2">
                <Switch
                  id="is_active"
                  checked={formData.is_active}
                  onCheckedChange={(checked) => setFormData({...formData, is_active: checked})}
                />
                <Label htmlFor="is_active">启用此设置</Label>
              </div>

              <div className="flex justify-end gap-3 pt-4 border-t">
                <Button type="button" variant="outline" onClick={handleCancel}>
                  取消
                </Button>
                <Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isQueryingCoords}>
                  {editingConfig ? '更新设置' : '创建设置'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {isLoading ? (
          Array(4).fill(0).map((_, i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader>
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="h-3 bg-gray-200 rounded w-1/2"></div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="h-3 bg-gray-200 rounded"></div>
                  <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                </div>
              </CardContent>
            </Card>
          ))
        ) : configs.length === 0 ? (
          <div className="col-span-full">
            <Card className="text-center py-12">
              <CardContent>
                <Settings className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无系统设置
                </h3>
                <p className="text-gray-500 mb-6">
                  添加系统设置来自定义应用行为
                </p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加设置
                </Button>
              </CardContent>
            </Card>
          </div>
        ) : (
          configs.map((config) => {
            const isRequired = isSystemRequired(config.configKey);

            // Determine display value based on type or specific configKey
            const displayValue = config.configKey.includes('map_cache_region')
              ? JSON.stringify(config.config_value, null, 2) // For map_cache_region, config.config_value IS the JSON object
              : config.config_value.type === 'json'
                ? JSON.stringify(config.config_value.value, null, 2)
                : config.config_value.value?.toString();
            
            // Determine display name
            const displayName = config.configKey.includes('map_cache_region')
                ? config.config_value.name || config.configKey // For map_cache_region, name is inside config_value
                : config.config_value.name || config.configKey;


            return (
              <Card key={config.id} className={`shadow-lg border-0 ${isRequired ? 'ring-2 ring-blue-200' : ''}`}>
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                        isRequired ? 'bg-blue-100' : 'bg-green-100'
                      }`}>
                        <Settings className={`w-6 h-6 ${
                          isRequired ? 'text-blue-600' : 'text-green-600'
                        }`} />
                      </div>
                      <div>
                        <CardTitle className="lg:text-lg font-bold text-gray-900 flex items-center gap-2">
                          {displayName}
                          {isRequired && (
                            <Badge className="bg-blue-100 text-blue-700 text-xs">
                              系统必需
                            </Badge>
                          )}
                        </CardTitle>
                        <div className="flex items-center gap-2 mt-1">
                          <Badge variant={config.is_active ? "default" : "secondary"}>
                            {config.is_active ? "活跃" : "未活跃"}
                          </Badge>
                          <Badge variant="outline" className="text-xs">
                            {config.configKey.includes('map_cache_region') ? 'json' : config.config_value.type}
                          </Badge>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleEdit(config)}
                        className="w-8 h-8"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      {!isRequired && (
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleSafeDelete(config)}
                          className="w-8 h-8 text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </CardHeader>

                <CardContent className="pt-0">
                  <div className="space-y-3">
                    <div className="bg-gray-50 p-3 rounded-lg">
                      <div className="text-xs text-gray-500 mb-1">当前值:</div>
                      <div className="font-mono text-sm break-all">
                        {displayValue}
                      </div>
                    </div>

                    {config.description && (
                      <p className="text-sm text-gray-600">
                        {config.description}
                      </p>
                    )}

                    <div className="text-xs text-gray-500 pt-2 border-t flex justify-between">
                      <span>配置键: {config.configKey}</span>
                      {isRequired && (
                        <span className="text-blue-600 font-medium">不可删除</span>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>
    </div>
  );
}
